<script setup lang="ts">
import Pagination from "@/components/pagination/index.vue";
import InfoDialog from "./dialog/goodsInfo.vue";
import EditDialog from "./dialog/edti.vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { fetchGoodsList, fetchPostGoods, fetchPutGoods } from '@/api/goods'
import { filterDate } from '@/utils/format'
import type { FormInstance, FormRules } from "element-plus";

const props = defineProps({
  // 物资存在那个库里面
  category: {
    type: Number,
    default: 0,
  },
})
let showInfoDialog = ref(false); // 是否展示物资信息编辑框
let goodsFormDialog = ref(false);
/**
 * 查看
 */
const checkForm = (value: boolean) => {
  // TODO 弹出查看表单
  goodsFormDialog.value = value;
};

/**
 * 下架
 */
const suspendGoods = (row: { id: any; }) => {
  let str = ref('启用')
  let category =ref(1)
  props.category == 0 ? str.value = '停用' : str.value = '启用'
  props.category == 0 ? category.value = 1 : category.value = 0
  ElMessageBox.confirm(`当前操作会${str.value}物资，是否继续？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      fetchPutGoods({ id: row.id, category: category.value }).then((res: { code: number; }) => {
        if (res.code == 200) {
          ElMessage({
            message: '操作成功',
            type: 'success'
          })
        }
        showInfoDialog.value = false
        getPageList()
      })
    })
    .catch(() => { });
};

/**
 * 新增物资入库
 * @param type add表示点击新增，edit表示点击修改
 * @param isShow 关闭或者展示弹框
 * @param row 编辑弹框时将数据传过来
 */
/**
 * 新增/编辑物资
 * @param isShow 关闭或者展示弹框
 * @param isAdd 是否是新增（true是新增，false是编辑）
 * @param row 编辑弹框时将数据传过来
 */
const handleInfo = (isShow: boolean, isAdd: boolean, row: any) => {
  showInfoDialog.value = isShow;
  if (isAdd) {
    title.value = '新增物资'
  } else {
    title.value = '编辑物资'
    ruleForm.id = row.id
    ruleForm.type = row.type
    ruleForm.name = row.name
    ruleForm.price = row.price
    ruleForm.unit = row.unit
    ruleForm.goodsInfo = row.goodsInfo
    ruleForm.inputNum = row.inputNum
  }
};
// 表单数据
let tableData = reactive([])
// 实际传递的条件
const listQuery = reactive({
  currentPage: 1,
  name: undefined, // 名称
  type: 1, // 类型
  status: undefined, // 招新状态
  pageSize: 10,
  form: undefined, // 活动形式
  category: props.category
})
// 显示在界面上的查询条件
const showQuery = reactive({
  currentPage: 1,
  name: undefined, // 名称
  type: undefined, // 类型
  status: undefined, // 招新状态
  form: undefined, // 活动形式
})
const total = ref<number>(0)// 列表总数
// 查询
const handleSearch = () => {
  getPageList()
}
const tableLoading = ref(false)
// 获取列表
const getPageList = async () => {
  tableLoading.value = true
  listQuery.name = showQuery.name
  listQuery.status = showQuery.status
  const res = await fetchGoodsList(listQuery)
  const { currentPage, data } = res.data
  listQuery.currentPage = showQuery.currentPage = currentPage
  total.value = res.data.total
  tableData = data
  tableLoading.value = false
}
onMounted(() => {
  getPageList()
})
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  // 重置验证规则
  if (!formEl) return;
  showInfoDialog.value = false
  ruleForm = {
    id: 0,
    type: 0,
    name: '', // 名称
    price: "", // 单价
    inputNum: "", // 数量
    unit: "", // 单位
    goodsInfo: "", // 备注
    category: 0,
  }
  formEl.resetFields();
};
let ruleForm = reactive({
  id: 0,
  type: 0,
  name: '', // 名称
  price: "", // 单价
  inputNum: "", // 数量
  unit: "", // 单位
  goodsInfo: "", // 备注
  category: 0,
});
const typeOptions = [
  {
    value: 0,
    label: '领用物资'
  },
  {
    value: 1,
    label: '借用物资'
  }
]
const ruleFormRef = ref<FormInstance>();
const title = ref('')
const rules = reactive<FormRules>({
  type: [{ required: true, message: "请选择物资类型", trigger: "change" }],
  name: [{ required: true, message: "请输入物资名称", trigger: "change" }],
  price: [{ required: true, message: "请输入物资单价", trigger: "change" }],
  inputNum: [{ required: true, message: "请输入入库数量", trigger: "change" }],
  unit: [{ required: true, message: "请输入入库单位", trigger: "change" }],
  goodsInfo: [{ required: true, message: "请输入物资信息", trigger: "change" }],
});

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value === '新增物资') {
        fetchPostGoods(ruleForm).then((res: { code: number; }) => {
          if (res.code == 200) {
            ElMessage({
              message: '操作成功',
              type: 'success'
            })
          }
          showInfoDialog.value = false
          getPageList()
        })
      } else {
        fetchPutGoods(ruleForm).then((res: { code: number; }) => {
          if (res.code == 200) {
            ElMessage({
              message: '操作成功',
              type: 'success'
            })
          }
          showInfoDialog.value = false
          getPageList()
        })
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<template>
  <div class="goods-form-container">
    <div class="header flex justify-between items-center">
      <div class="flex items-center justify-between">
        <el-input v-model="showQuery.name" placeholder="根据名称查询" clearable />
        <el-button type="primary" :icon="Search" class="btn-green" @click="handleSearch()">查询</el-button>
      </div>
      <div class="add-table" v-if="props.category == 0">
        <el-button type="primary" size="large" :icon="Plus" class="btn-green"
          @click="handleInfo(true, true, {})">新增物资入库</el-button>
      </div>
    </div>
    <el-table :data="tableData" stripe style="min-height: 40rem">
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="name" label="名称" show-overflow-tooltip />
      <el-table-column prop="price" label="单价(元)" sortable />
      <el-table-column prop="totalInput" label="累计入库" sortable>
        <template #default="scope">
          <div>{{ scope.row.totalInput + scope.row.unit }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="入库时间">
        <template #default="scope">
          <div>{{ filterDate(scope.row.createdAt) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="报废时间" v-if="props.category == 2">
        <template #default="scope">
          <div>{{ filterDate(scope.row.updatedAt) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsInfo" label="物资信息" show-overflow-tooltip />
      <el-table-column prop="stockNum" label="当前库存" sortable>
        <template #default="scope">
          <div>{{ scope.row.stockNum + scope.row.unit }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <div class="theme-success" v-if="props.category == 0 && scope.row.stockNum > 10">可借用</div>
          <div class="theme-warn" v-if="props.category == 0 && scope.row.stockNum <= 10 && scope.row.stockNum > 0">库存紧张
          </div>
          <div class="theme-error" v-if="props.category == 0 && scope.row.stockNum == 0">暂无库存</div>
          <div class="theme-warn" v-if="props.category == 1">已停用</div>
          <div class="theme-error" v-if="props.category == 2">暂不可用</div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="操作" v-if="props.category  == 0 || props.category  == 1">
        <template #default="scope">
          <div class="theme-success">
            <!-- <el-button type="primary" link @click="checkForm(true)">查看</el-button> -->
            <el-button type="primary" link @click="handleInfo(true, false, scope.row)" >编辑</el-button>
            <el-button type="primary" link @click="suspendGoods(scope.row)" v-if="props.category == 0">停用</el-button>
            <el-button type="primary" link @click="suspendGoods(scope.row)" v-if="props.category == 1">启用</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :total="total" v-model:page="listQuery.currentPage" v-model:limit="listQuery.pageSize" hide-on-single-page
      @pagination="getPageList" />

    <!-- 查看弹框 -->
    <InfoDialog ref="infoDialog" :goodsFormDialog="goodsFormDialog" @closeDialog="checkForm(false)" />
    <!-- 编辑弹框 -->
    <!-- <EditDialog :show-info-dialog="showInfoDialog" @closeDialog="handleInfo(false)" :form-data="formData"></EditDialog> -->

    <!-- 编辑弹框 -->
    <div class="el-dialog-25">
      <el-dialog v-model="showInfoDialog" :title="title" @close="resetForm(ruleFormRef)">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
          <el-form-item label="物资类型：" prop="type" class="el-form-item-full">
            <el-select v-model="ruleForm.type" class="m-2" placeholder="请选择物资类型" disabled>
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="物资名称：" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入物资名称" clearable />
          </el-form-item>
          <el-form-item label="物资单价(元)：" prop="price">
            <el-input v-model="ruleForm.price" placeholder="请输入物资单价" clearable />
          </el-form-item>
          <el-form-item label="入库数量：" prop="inputNum">
            <el-input v-model="ruleForm.inputNum" placeholder="请输入入库数量" clearable :disabled="title === '编辑物资'" />
          </el-form-item>
          <el-form-item label="入库单位：" prop="unit">
            <el-input v-model="ruleForm.unit" placeholder="请输入入库单位" clearable />
          </el-form-item>
          <el-form-item label="入库备注：" prop="goodsInfo">
            <el-input v-model="ruleForm.goodsInfo" maxlength="100" show-word-limit type="textarea"
              placeholder="可输入该物资的一些入库备注信息" clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetForm(ruleFormRef)" class="btn-white">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" class="btn-green">
              确定
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

  </div>
</template>

<style  lang="scss">
.goods-form-container {
  .header {
    height: 70px;

    .el-input {
      margin-right: 20px;
    }
  }
}
</style>
